package com.laowang.project.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.laowang.common.utils.SecurityUtils;
import com.laowang.common.utils.StringUtils;
import com.laowang.common.utils.bean.BeanUtils;
import com.laowang.project.system.domain.MyCyhActivity;
import com.laowang.project.system.domain.MyCyhActivityPhone;
import com.laowang.project.system.domain.SysRole;
import com.laowang.project.system.domain.vo.JsonObjectParse;
import com.laowang.project.system.domain.vo.MyCyhActivitySignVo;
import com.laowang.project.system.mapper.SysRoleMapper;
import com.laowang.project.system.service.MyCyhActivityPhoneService;
import com.laowang.project.system.service.MyCyhActivityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;


import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.laowang.framework.aspectj.lang.annotation.Log;
import com.laowang.framework.aspectj.lang.enums.BusinessType;

import org.springframework.web.bind.annotation.*;
import com.laowang.project.system.domain.MyCyhActivitySign;
import com.laowang.project.system.service.MyCyhActivitySignService;
import com.laowang.framework.web.controller.BaseController;
import com.laowang.framework.web.domain.AjaxResult;
import com.laowang.common.utils.poi.ExcelUtil;
import com.laowang.framework.web.page.TableDataInfo;

/**
 * 活动报名Controller
 *
 * @author laowang
 * @date 2023-05-22
 */
@Api(tags = "活动报名接口")
@RestController
@RequestMapping("/activitySign")
public class MyCyhActivitySignController extends BaseController {
    @Autowired
    private MyCyhActivitySignService myCyhActivitySignService;

    @Autowired
    private MyCyhActivityService myCyhActivityService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private MyCyhActivityPhoneService myCyhActivityPhoneService;

    @ApiOperation(value = "小程序端 活动报名核销",notes = "")
    @GetMapping("/web/checkSign")
    public AjaxResult checkSign(Integer codeId) {
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        MyCyhActivitySign myCyhActivitySign = myCyhActivitySignService.selectMyCyhActivitySignById(codeId);
        if (myCyhActivitySign !=null){
            if (myCyhActivitySign.getAuditStatus().equals(1)){
                return AjaxResult.error("已经核销过了!");
            }
            MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(myCyhActivitySign.getActivityId());
            if (myCyhActivity.getCheckUser() == null ||  myCyhActivity.getCheckUser().equals(0) ){
                return AjaxResult.error("该活动未设置核销人");
            }

            if (!mid.equals(myCyhActivity.getCheckUser())){
                return AjaxResult.error("该账号非该活动核销者");
            }

            myCyhActivitySign.setAuditStatus(1);
            myCyhActivitySign.setCheckTime(new Date());
            myCyhActivitySignService.updateMyCyhActivitySign(myCyhActivitySign);
        }else {
            return AjaxResult.error("该报名记录未找到");
        }
        return AjaxResult.success("操作成功");
    }

    @ApiOperation(value = "小程序端 活动报名",notes = "")
    @PostMapping("/web/add")
    public AjaxResult webadd(@RequestBody MyCyhActivitySign myCyhActivitySign) {

        myCyhActivitySignService.insertMyCyhActivitySignWeb(myCyhActivitySign);
        return AjaxResult.success("操作成功");
    }

    @ApiOperation(value = "小程序端 活动报名",notes = "")
    @PostMapping("/web/add1")
    public AjaxResult webadd1(@RequestBody MyCyhActivitySign myCyhActivitySign) {

        myCyhActivitySignService.insertMyCyhActivitySignWeb1(myCyhActivitySign);
        return AjaxResult.success("操作成功",myCyhActivitySign.getId());
    }

    @ApiOperation(value = "小程序端 已报名的活动",notes = "")
    @PostMapping("/web/mySign")
    public AjaxResult mySign() {
        MyCyhActivitySign myCyhActivitySign = new MyCyhActivitySign();
        Integer mid = SecurityUtils.getLoginUser().getWxUser().getMid();
        myCyhActivitySign.setUserId(mid);
        List<MyCyhActivitySign> myCyhActivitySigns = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);
        List<Integer> collect = myCyhActivitySigns.stream().map(MyCyhActivitySign::getActivityId).collect(Collectors.toList());
        List<MyCyhActivity> list = myCyhActivityService.selectByIdList(collect);

        return AjaxResult.success("操作成功",list);
    }

    /**
     * 查询活动报名列表
     */
    @ApiOperation(value = "查询活动报名列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:list')")
    @GetMapping("/list")
    public TableDataInfo list(MyCyhActivitySign myCyhActivitySign) {

        /*MyCyhActivity myCyhActivity =new MyCyhActivity();
        myCyhActivity.setAuditStatus(1);*/
        List<MyCyhActivity> myCyhActivities = myCyhActivityService.selectMyCyhActivityList(null);
        Map<Integer, String> collect = myCyhActivities.stream().collect(Collectors.toMap(MyCyhActivity::getId, MyCyhActivity::getTitle));

        List<MyCyhActivitySign> list = new ArrayList<>();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //不是管理员
        if (!userId.equals(1L)  ){
            List<SysRole> sysRoles = sysRoleMapper.selectRolePermissionByUserId(userId);
            // 是 活动管理者
            Boolean b = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("activityManager"));
            if (b){
                List<Integer> listIds = myCyhActivityService.selectActivityIdByCreateBy(userId);
                if (listIds.size()>0){
                    myCyhActivitySign.setListIds(listIds);
                    startPage();
                    list = myCyhActivitySignService.selectMyCyhActivitySignListByCreateBy(myCyhActivitySign);
                    /*MyCyhActivityPhone myCyhActivityPhone = myCyhActivityPhoneService.selectMyCyhActivityPhoneById(1);
                    if (myCyhActivityPhone != null && myCyhActivityPhone.getIsLook().equals(1)){
                        for (MyCyhActivitySign cyhActivitySign : list) {
                            String mobile = cyhActivitySign.getMobile();
                            String phone =   mobile.substring(0,3)+"****" + mobile.substring(7);
                            cyhActivitySign.setMobile(phone);
                        }
                    }*/
                }
            }

            Boolean b1 = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("cheyouhui"));
            if (b1){
                //是车友会账户
                startPage();
                list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);
            }

            Boolean b2 = sysRoles.stream().anyMatch(sysRole -> sysRole.getRoleKey().equals("exportManager"));
            if (b2){
                //活动导出人员
                startPage();
                list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);
            }


        }else {
            startPage();
            list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);
        }

        //startPage();
        //list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);

        for (MyCyhActivitySign cyhActivitySign : list) {
            String s1 = collect.get(cyhActivitySign.getActivityId());
            cyhActivitySign.setActivityName(s1);
            //String s ="";
            /*String rules = cyhActivitySign.getRules();
            if (StringUtils.isNotEmpty(rules)){
                List<JsonObjectParse> jsonObjectParses = JSONObject.parseArray(rules, JsonObjectParse.class);
                //System.out.println(jsonObjectParses);
                if (jsonObjectParses.size()>0){
                    for (JsonObjectParse jsonObjectPars : jsonObjectParses) {
                        s += "姓名:"+jsonObjectPars.get姓名()+"   "+ "身份证号:"+jsonObjectPars.get身份证号()+"\n";
                    }
                    //s+= "姓名:金刚   身份证号:12333";
                    cyhActivitySign.setRules(s);
                }
            }*/

        }
         return getDataTable(list);
    }

    /**
     * 导出活动报名列表
     */
    @ApiOperation(value = "导出活动报名列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:export')")
    @Log(title = "活动报名", businessType = BusinessType.EXPORT)
    @GetMapping("/export1")
    public AjaxResult export1(MyCyhActivitySign myCyhActivitySign) {
        Integer activityId = myCyhActivitySign.getActivityId();
        MyCyhActivity myCyhActivity = myCyhActivityService.selectMyCyhActivityById(activityId);
        /*if (myCyhActivity.getAtimeEnd().after(new Date())){
            return AjaxResult.error("活动未结束,不支持导出");
        }*/
        List<MyCyhActivitySign> list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);
        List<MyCyhActivitySignVo> list1 =new ArrayList<>();
        for (MyCyhActivitySign cyhActivitySign : list) {
            MyCyhActivitySignVo myCyhActivitySignVo = new MyCyhActivitySignVo();
            BeanUtils.copyProperties(cyhActivitySign,myCyhActivitySignVo);
            list1.add(myCyhActivitySignVo);
        }
        System.out.println(list1);
        ExcelUtil<MyCyhActivitySignVo> util = new ExcelUtil<MyCyhActivitySignVo>(MyCyhActivitySignVo.class);
        return util.exportExcel(list1, "activitySignVo");
    }

    @ApiOperation(value = "导出活动报名列表",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:export')")
    //@Log(title = "活动报名", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAbc")
    public AjaxResult exportAbc(MyCyhActivitySign myCyhActivitySign) {
        //startPage();
        List<MyCyhActivitySign> list = myCyhActivitySignService.selectMyCyhActivitySignList(myCyhActivitySign);

        MyCyhActivity myCyhActivity =new MyCyhActivity();
        myCyhActivity.setAuditStatus(1);
        List<MyCyhActivity> myCyhActivities = myCyhActivityService.selectMyCyhActivityListWeb(myCyhActivity);
        Map<Integer, String> collect = myCyhActivities.stream().collect(Collectors.toMap(MyCyhActivity::getId, MyCyhActivity::getTitle));
        for (MyCyhActivitySign cyhActivitySign : list) {
            String s1 = collect.get(cyhActivitySign.getActivityId());
            cyhActivitySign.setActivityName(s1);
        }
        ExcelUtil<MyCyhActivitySign> util = new ExcelUtil<MyCyhActivitySign>(MyCyhActivitySign.class);
        return util.exportExcel(list, "activitySign");
    }

    /**
     * 获取活动报名详细信息
     */
    @ApiOperation(value = "获取活动报名详细信息",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        return AjaxResult.success(myCyhActivitySignService.selectMyCyhActivitySignById(id));
    }

    /**
     * 新增活动报名
     */
    @ApiOperation(value = "新增活动报名",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:add')")
    @Log(title = "活动报名", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MyCyhActivitySign myCyhActivitySign) {
        return toAjax(myCyhActivitySignService.insertMyCyhActivitySign(myCyhActivitySign));
    }

    /**
     * 修改活动报名
     */
    @ApiOperation(value = "修改活动报名",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:edit')")
    @Log(title = "活动报名", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MyCyhActivitySign myCyhActivitySign) {
        return toAjax(myCyhActivitySignService.updateMyCyhActivitySign(myCyhActivitySign));
    }

    /**
     * 删除活动报名
     */
    @ApiOperation(value = "删除活动报名",notes = "")
    @PreAuthorize("@ss.hasPermi('my:activitySign:remove')")
    @Log(title = "活动报名", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(myCyhActivitySignService.deleteMyCyhActivitySignByIds(ids));
    }
}
